<?php


namespace App\Http\Controllers;


use App\Models\Business;
use App\Models\Order;
use App\Models\ServicePersonnel;
use App\Models\ServiceProject;
use Closure;
use EasyWeChat\Kernel\Contracts\Server as ServerInterface;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Pay\Application;
use EasyWeChat\Pay\Message;
use EasyWeChat\Pay\Server;
use EasyWeChat\Pay\Utils;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MiniAppPayController extends Controller
{

    /**
     * @var Application
     */
    private $app;

    public function __construct()
    {
        $config = [
            'mch_id' => env('MINIAPP_MCHID'),
            // 商户证书
            'private_key' => public_path('pay') . '/apiclient_key.pem',
            'certificate' => public_path('pay') . '/apiclient_cert.pem',
            // v3 API 秘钥
            'secret_key' => env('MINIAPP_SECRET_KEY'),
            // v2 API 秘钥
            'v2_secret_key' => env('MINIAPP_V2_SECRET_KEY'),

            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
//            'platform_certs' => [
//                '/path/to/wechatpay/cert.pem',
//            ],

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw' => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
            ],
        ];

        $this->app = new Application($config);
    }

    public function pay()
    {
        $business_id = request()->post('id');

        $money = Business::query()->where('id', '=', $business_id)->value('money');
//        $money = 0.01;

        $openid = Auth::user()['openid'];
        $order = new Order();
        $order->b_id = $business_id;
        $order->title = "支付";
        $order->out_trade_no = 'xcx' . time() . rand(1, 99999);
        $order->amount = $money;
        $order->save();

        $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", [
            "mchid" => env('MINIAPP_MCHID'), // <---- 请修改为您的商户号
            "out_trade_no" => $order->out_trade_no,
            "appid" => env('MINIAPP_APP_ID'), // <---- 请修改为服务号的 appid
            "description" => $order->title,
            "notify_url" => getRootUrl() . "/v1/miniapp/pay/callback",
            "amount" => [
                "total" => intval($money * 100),
                "currency" => "CNY"
            ],
            "payer" => [
                "openid" => $openid
            ]
        ]);
        $data = $response->toArray(false);
        if (isset($data['code'])) {
            return Json(0, $data['message'],);
        }
        $appId = env('MINIAPP_APP_ID');
        $signType = 'RSA'; // 默认RSA，v2要传MD5
        $utils = $this->app->getUtils();
        $config = $utils->buildMiniAppConfig($data['prepay_id'], $appId, $signType);
        return Json(1, 'ok', $config);


    }

    public function callback()
    {
        Log::info(json_encode(request()->post()));
        /**
         * @var $server Server
         */
        $server = $this->app->getServer();
        $message = $server->getRequestMessage();
        if($message->trade_state=="SUCCESS"){
            $out_trade_no=$message->out_trade_no;
            DB::beginTransaction();
            try {
                $order=Order::query()->where('out_trade_no','=',$out_trade_no)->where('state','=',0)->first();
                if(empty($order)){
                    Log::error("订单不存在");
                    return ;
                }
                $order->extend=json_encode($message->getOriginalAttributes());
                $order->order_id=$message->transaction_id;
                $order->state=1;
                $order->save();
                $business= Business::query()->where('id','=',$order->b_id)->first();
                $business->state=1;

                DB::commit();
                $work_account=ServicePersonnel::query()->where('id','=',$business->personnel_id)->value('work_account','');
                if(!empty($work_account)){
                    //订单成功 发送 消息到企业微信
                    try {
                        $service=new \App\Http\Service\WordService();
                        $res= $service->sendMessage($work_account,$order->out_trade_no,$business->id);
                        if(isset($res['errmsg'])&&$res['errmsg']=="ok"){
                            $business->is_notify_personnel=1;
                        }
                        Log::info('通知日志：'.json_encode($res));
                    }catch (\Exception $exception){
                        Log::error('通知日志：'.$exception->getMessage() );

                    }
                }
                $business->save();
            }catch (\Exception $exception){
                DB::rollBack();
                Log::error("支付失败：".$exception->getMessage());
            }
            $trade_state=$message->trade_state;
            $transaction_id=$message->transaction_id;
            $total=$message['amount']['total'];
            return json_encode(['code'=>'SUCCESS','message'=>'OK']);
        }else{
            return json_encode(['code'=>'FAIL','message'=>'失败']);
        }


    }


}
